import { createRouter, createWebHistory } from 'vue-router'

import layout from '@/layout/index.vue'

import { userPermissions } from '@/api/user/index.js'
import Cookies from 'js-cookie'
import { generateRoute } from '../../utils/index.js'

const routes = [
    // 登录
    {
        path: '/login',
        name: 'Login',
        meta: {
            title: '登录'
        },
        component: () => import('@/views/login.vue')
    },
    {
        path: '/404',
        name: '404',
        meta: {
            title: '404'
        },
        component: () => import('@/views/404.vue')
    },
    {
        path: '/',
        name: "Layout",
        redirect: '/index',
        component: layout,
        children: [
            {
                path: 'index', // 不用加 / 会自动拼接父路由 path
                name: "Index",
                meta: {
                    title: '首页'
                },
                component: () => import('../views/index.vue'),
            },
            {
                path: 'userInfo',
                name: "UserInfo",
                meta: {
                    title: '用户信息'
                },
                component: () => import('../views/user/userInfo.vue'),
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 动态路由
async function loadAsyncRoutes() {
    let token = Cookies.get('gn-token')
    const modules = import.meta.glob("../views/**/*.vue");
    if (token) {
        try {
            const { data } = await userPermissions()
            let routes = generateRoute(data.data.menuList)
            routes.map(route => {
                // let url = `./../views/${route.component}.vue`
                // route.component = () => import(/* @vite-ignore */ url)
                route.component = modules[`../views${route.component}.vue`]
                router.addRoute('Layout', route)
            })
        } catch (error) {
            console.log(error);
        }
    }
}

// 路由守卫
let oneRun = true; //通过oneRun变量控制 避免陷入死循环
router.beforeEach(async (to, from, next) => {
    // 首次登录动态加载路由
    if (from.name == 'Login') {
        await loadAsyncRoutes()
    }
    // 刷新页面重新动态加载路由
    if (oneRun) {
        oneRun = false;//必须在loadAsyncRoutes() 执行
        await loadAsyncRoutes()
        return next({ ...to, replace: true })// 必不可少的，确保你的动态路由创建成功再去执行其它代码
    }
    if (router.hasRoute(to.name)) {
        document.title = '顾鸟 | ' + to.meta.title
        next()
    } else {
        // loadAsyncRoutes()
        next('/404')
    }
})

export default router